<template>
  <view id="storeDetail" class="page">
    <swiper
      class="swapper"
      autoplay="true"
      indicator-active-color="#0BE0DE"
      indicator-color="#8FD2D4"
      :indicator-dots="true"
      :circular="true"
    >
      <view v-for="(item, index) in swiperImgUrls" :key="index">
        <swiper-item>
          <image
            class="image"
            :src="imgUrl + item"
            @tap="onTapPreviewImg(item, swiperImgUrls)"
          />
        </swiper-item>
      </view>
    </swiper>
    <view class="store">
      <view class="title">
        <view class="name" v-if="store.community">{{
          store.community.name
        }}</view>
        <view class="distance">距您{{ distance }}km</view>
      </view>
      <view class="address">
        <image class="icon-left" src="../../../image/icon_location.png" />
        <view class="text" v-if="store.community">{{
          store.community.address
        }}</view>
        <image class="map" src="../../../image/icon_map.png" @tap="onTapMap" />
        <image
          class="phone"
          src="../../../image/icon_phone2.png"
          @tap="onTapCallPhone"
        />
      </view>
      <view class="row-score">
        <rate-star
          :percent="score * 20"
          width="10"
          height="12"
          id="rateStarTotal"
          disabled
        />
        <view class="text"> {{ score }}<text class="text2">分</text></view>
        <view class="text">
          {{ totalCount }}<text class="text2">条评论</text></view
        >
      </view>
    </view>
    <view class="box-service">
      <view class="box-service-title">
        <image
          class="icon-appointment"
          src="../../../image/icon_appointment.png"
        />
        <text class="service-name">预约服务</text>
      </view>
      <view v-if="store.community && store.community.reservationServices">
        <view
          v-for="(service, index) in store.community.reservationServices"
          :key="index"
          class="item-service"
        >
          <image class="img" :src="imgUrl + service.url" />
          <view class="name">{{ service.name }}</view>
          <view
            v-if="hasPhone"
            class="btn-appointment"
            @tap="onItemAppointment(service)"
            >预约</view
          >
          <button
            v-else
            openType="getPhoneNumber"
            @GetPhoneNumber="onGetPhoneNumber"
            class="btn-appointment"
            size="mini"
          >
            预约
          </button>
        </view>
      </view>
      <view class="text-tip"
        >温馨提示：若没有找到需要的预约项目，可直接预约业务分类，
        并在订单备注中填写需要进行的项目。</view
      >
    </view>
    <view class="box-evaluate">
      <view class="box-evaluate-title">
        <image class="icon-evaluate" src="../../../image/icon_evaluate.png" />
        <text class="evaluate-name">用户评价</text>
        <text class="evaluate-count">({{ totalCount }}条)</text>
      </view>
      <view class="box-evaluate-total-score">
        <view class="box1">
          <view class="text1">{{ score }}</view>
          <rate-star
            :percent="score * 20"
            width="10"
            height="12"
            id="rateStarStore"
            disabled
          />
        </view>
        <view class="box-right" v-if="store.categoryEvaluates">
          <view
            class="box2"
            v-for="(item, index) in store.categoryEvaluates"
            :key="index"
          >
            <view class="text-top">{{ item.category }}</view>
            <view class="text-score">{{ item.avgScore }}</view>
          </view>
        </view>
      </view>
      <view class="box-tag">
        <view
          v-for="(item, index) in serviceList"
          :key="index"
          v-model="serviceTag"
          :class="serviceTag == index ? tagSelect : tagNormal"
          @tap="onTapServiceTag(index)"
          >{{ item.servicaName }}({{ item.quantity }})</view
        >
      </view>
    </view>
    <view class="evaluate-list" v-if="evaluateList">
      <view v-for="(item, index) in evaluateList" :key="index">
        <view class="box-header">
          <image
            v-if="!item.isAnonymous && item.order.headImgUrl"
            class="img-header"
            :src="item.order.headImgUrl"
          />
          <image
            v-else
            class="img-header"
            src="../../../image/img_header.png"
          />
          <view class="header-name">
            <view v-if="item.isAnonymous">匿名用户</view>
            <view v-else>{{ item.order.nickName || "匿名用户" }}</view>
            <rate-star
              :id="'rateStarEvaluateItem' + index"
              :percent="item.score * 20"
              width="8"
              height="9"
              disabled
            />
          </view>
          <text class="time">{{ item.createTime }}</text>
        </view>
        <view class="text-evaluate-content" v-if="item.content">{{
          item.content
        }}</view>
        <view v-if="item.imageUrlList" class="evaluate-list-img-box">
          <view
            v-for="(itemImg, indexImg) in item.imageUrlList"
            :key="indexImg"
          >
            <image
              class="evaluate-img"
              :src="imgUrl + itemImg"
              mode="aspectFill"
              @tap="onTapPreviewImg(itemImg, item.imageUrlList)"
            />
          </view>
        </view>
        <view v-if="item.children">
          <view
            class="evaluate-store-reply-box"
            v-for="(reply, indexReply) in item.children"
            :key="indexReply"
          >
            <view class="evaluate-store-reply-name">门店回复:</view>
            <view class="evaluate-store-reply-content">{{
              reply.content
            }}</view>
          </view>
        </view>
        <view
          class="evaluate-item-service-name"
          v-if="item.order && item.order.service"
        >
          <text class="title">服务内容:</text>
          <text class="name">{{ item.order.service.name }}</text>
        </view>
        <view
          v-if="index != evaluateList.length - 1"
          class="item-divider"
        ></view>
      </view>
      <view v-if="hasMore && evaluateList.length > 0" class="no-more"
        >上滑查看更多评价…</view
      >
      <view v-else-if="!hasMore && evaluateList.length > 0" class="no-more"
        >没有更多评价啦</view
      >
    </view>
    <view v-if="evaluateList.length == 0" class="no-more"
      >当前没有评价信息~</view
    >
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./storeDetail.less";
import { getMapDistance, isFastClick } from "../../../check.js";
import { request } from "../../../util/axios.js";
import rateStar from "../../../components/rate-star/rate-star.vue";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
const API_CarCode = process.env.IOParking.API_CARCODE;
const apiBaseUrl = process.env.IOParking.API_HOST; //请求头部
var common = require("../../../common.js");
const openIdMock = "oRPxj5bi2JB-id96cJ_s1wBWmjAo";
const mobileMock = "18039670989";
// 获取位置
export default {
  name: "storeDetail",
  data() {
    return {
      communityId: 87163114566341, //默认门店
      imgUrl: process.env.IOParking.IMAGE_BASE,
      swiperImgUrls: [],
      store: {}, //门店信息
      paginations: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      hasMore: true,
      isFirstLoad: true,
      score: 5.0,
      totalCount: 0,
      serviceList: [],
      evaluateList: [],
      serviceTag: 0, //已选择的tag
      tagNormal: "tag-normal",
      tagSelect: "tag-select",
      latitude: 0, //当前坐标纬度
      longitude: 0, //当前坐标经度
      distance: 0, //当前位置距离门店km
      hasPhone: false,
      service: {},
    };
  },
  created() {},
  //mixins:[authorize],
  components: { rateStar },
  mounted() {},

  onLoad: function (options) {
    if (options.communityId) {
      this.communityId = options.communityId;
    }
    this.getStoreInfo();
    this.getEvaluateList();
    this.getLocation();
    try {
      var mobile = Taro.getStorageSync("mobile");
      if (!mobile) {
        this.wx_login();
      } else {
        this.hasPhone = true;
      }
    } catch (error) {
      this.wx_login();
    }
  },
  //触发了上拉加载，做些什么
  onReachBottom() {
    if (this.hasMore) {
      this.paginations.pageIndex = this.paginations.pageIndex + 1;
      this.isFirstLoad = false;
      this.getEvaluateList();
    }
  },
  methods: {
    wx_getUser() {
      try {
        var nickName = Taro.getStorageSync("nickName");
        var avatarUrl = Taro.getStorageSync("avatarUrl");
        if (
          nickName &&
          avatarUrl &&
          nickName.length > 0 &&
          avatarUrl.length > 0
        ) {
          //以获取头像
          console.log("用户信息", nickName, avatarUrl);
          this.navigateToConfirm();
        } else {
          wx.getUserProfile({
            desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
              console.log("用户信息", JSON.stringify(res.userInfo));
              Taro.setStorage({
                key: "nickName",
                data: res.userInfo.nickName,
              });
              Taro.setStorage({
                key: "avatarUrl",
                data: res.userInfo.avatarUrl,
              });
              this.navigateToConfirm();
            },
            fail: (error) => {
              console.log("获取失败", error);
              this.navigateToConfirm();
            },
          });
        }
      } catch (error) {
        console.log("获取头像失败", error);
      }
    },
    wx_login() {
      api
        .getUserInfo({
          scope: "all",
        })
        .then((resp) => {
          console.log("微信authCode is：", JSON.stringify(resp));
          if (resp.success) {
            if (resp.data == "mock") {
              Taro.setStorage({
                key: "openId",
                data: openIdMock,
              });
              Taro.setStorage({
                key: "mobile",
                data: mobileMock,
              });
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      Taro.request({
        url: apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            let mobileRes = res.data.data.phoneNum;
            if (userOpenId) {
              Taro.setStorage({
                key: "openId",
                data: userOpenId,
              });
            }
            if (mobileRes) {
              Taro.setStorage({
                key: "mobile",
                data: mobileRes,
              });
              this.hasPhone = true;
            }
          }
        },
      });
    },
    onGetPhoneNumber({ detail }) {
      if (isFastClick()) {
        return;
      }
      console.log("授权手机号", JSON.stringify(detail));
      const { encryptedData, iv } = detail;
      if (encryptedData && iv) {
        this.authPhone(encryptedData, iv);
        Taro.showLoading({
          title: "授权中，请稍后",
          mask: true,
        });
      } else {
        //拒绝授权手机号
        this.hasPhone = false;
      }
    },
    authPhone(encryptedData, iv) {
      api
        .register({
          encryptedData: encryptedData,
          iv: iv,
          scope: "all",
        })
        .then((resp) => {
          Taro.hideLoading();
          if (resp.success) {
            console.log("用户注册 ", resp.data);
            if (resp.data == "mock") {
              this.hasPhone = true;
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("error ", resp.msg, "err code is ", resp.code);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //回到主页
    goHome() {
      api.openPage("home");
    },
    onTapPreviewImg(currentImg, list) {
      let imgUrls = list.map((item) => {
        item = this.imgUrl + item;
        return item;
      });
      Taro.previewImage({
        current: this.imgUrl + currentImg, // 当前显示图片的http链接
        urls: imgUrls, // 需要预览的图片http链接列表
      });
    },
    getStoreInfo() {
      if (!this.communityId) {
        return;
      }
      let url = API_CarCode + "community/getinfo";
      Taro.request({
        url: url,
        data: { id: this.communityId },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            this.store = res.data.data;
            let categoryEvaluates = res.data.data.categoryEvaluates.map(
              (item) => {
                item.avgScore =
                  item.avgScore == null ? 5.0 : item.avgScore.toFixed(1);
                return item;
              }
            );
            this.store.categoryEvaluates = categoryEvaluates;
            this.swiperImgUrls = this.store.community.imageUrls.split(",");
            if (
              this.store &&
              this.store.community &&
              this.latitude != 0 &&
              this.longitude != 0
            ) {
              this.distance = getMapDistance(
                this.latitude,
                this.longitude,
                this.store.community.latitude,
                this.store.community.longitude
              ).toFixed(1);
            }
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    getLocation() {
      Taro.getLocation({
        type: "gcj02", //返回可以用于 Taro.openLocation的经纬度
        isHighAccuracy: true, //高精度定位
        highAccuracyExpireTime: 4000, //高精度定位超时时间(ms)，指定时间内返回最高精度，该值3000ms以上高精度定位才有效果
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          console.log("定位:", this.latitude, this.longitude);
          if (
            this.store &&
            this.store.community &&
            this.store.community.longitude &&
            this.store.community.latitude
          ) {
            this.distance = getMapDistance(
              this.latitude,
              this.longitude,
              this.store.community.latitude,
              this.store.community.longitude
            ).toFixed(1);
          }
        },
        fail: (error) => {
          console.log("定位拒绝", error);
        },
      });
    },
    //点击地图
    onTapMap() {
      if (this.store.community.longitude && this.store.community.latitude) {
        let longitude = this.store.community.longitude;
        let latitude = this.store.community.latitude;
        Taro.openLocation({
          latitude,
          longitude,
          scale: 15,
        });
      } else {
        Taro.showToast({
          title: "未获取到门店坐标",
          icon: "none",
          duration: 1000,
          mask: true,
        });
      }
    },
    //点击打电话
    onTapCallPhone() {
      if (!this.store.community.mobile) {
        Taro.showToast({
          title: "未获取到门店电话",
          icon: "none",
          duration: 1000,
          mask: true,
        });
        return;
      }
      Taro.makePhoneCall({
        phoneNumber: this.store.community.mobile,
      });
    },
    onItemAppointment(service) {
      if (isFastClick()) {
        return;
      }
      let community = this.store.community;
      this.service = service;
      this.wx_getUser();
      // Taro.navigateTo({
      //   url: `../appointmentConfirm/appointmentConfirm?communityId=${community.id}&communityName=${community.name}
      //   &serviceId=${service.id}&serviceName=${service.name}&serviceImageUrl=${service.url}`,
      // });
    },
    navigateToConfirm() {
      let community = this.store.community;
      Taro.navigateTo({
        url: `../appointmentConfirm/appointmentConfirm?communityId=${community.id}&communityName=${community.name}
        &serviceId=${this.service.id}&serviceName=${this.service.name}&serviceImageUrl=${this.service.url}`,
      });
    },
    onGetUserInfo() {
      this.wx_getUser();
    },
    onTapServiceTag(index) {
      this.serviceTag = index;
      this.hasMore = true;
      this.isFirstLoad = true;
      this.paginations.pageIndex = 1;
      this.getEvaluateList();
    },
    //获取评价列表
    getEvaluateList() {
      if (!this.hasMore) {
        return;
      }
      Taro.showLoading({
        title: "正在加载",
        mask: true,
      });
      var serviceIdSelect = 0;
      if (this.serviceList.length > 0) {
        serviceIdSelect = this.serviceList[this.serviceTag].serviceId;
      }
      Taro.request({
        url: API_CarCode + "evaluate/pagelist",
        data: {
          pageIndex: this.paginations.pageIndex,
          pageSize: this.paginations.pageSize,
          filter: {
            communityId: this.communityId,
            serviceId: serviceIdSelect,
          },
        },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "POST",
        success: (res) => {
          Taro.hideLoading();
          console.log("评论", res.data);
          if (res.data.isSuccess) {
            let { category, totalCount, score } = res.data.data;
            let total = res.data.data.list.total; //总条数
            let list = res.data.data.list.list.map((item) => {
              item.createTime = common.formatTime(
                item.createTime.replace(/-/g, "/"),
                "Y-M-D"
              );
              if (item.imageUrls) {
                item.imageUrlList = item.imageUrls.split(",");
              }
              item.rateStarId = "rateEvaluate" + Math.random() * 10000000;
              return item;
            });
            if (score == 0) {
              score = 5.0;
            }
            this.score = score.toFixed(1);
            this.totalCount = totalCount;
            this.serviceList = category;
            this.serviceList.unshift({
              serviceId: 0,
              servicaName: "全部",
              quantity: this.totalCount,
            });
            if (this.isFirstLoad) {
              //刷新的
              this.evaluateList = list;
              this.paginations.total = list.length;
            } else {
              //上拉加载更多的
              this.evaluateList = this.evaluateList.concat(list);
              this.paginations.total += list.length; //总数
            }
            if (
              this.paginations.total >= total ||
              list.length < this.paginations.pageSize
            ) {
              this.hasMore = false;
            }
          } else {
            this.hasMore = false;
          }
        },
      });
    },
    //page-end
  },
};
</script>

